package com.wish.nettyhttpsimple;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpHeaders.Names.LOCATION;
import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;

import java.io.File;
import java.io.FileInputStream;
import java.io.RandomAccessFile;
import java.net.URLDecoder;
import java.util.regex.Pattern;

import javax.activation.MimetypesFileTypeMap;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;


/**
 * @author tantexian
 * @since 2016/7/14
 */
public class HttpFileHandle extends SimpleChannelInboundHandler<FullHttpRequest> {
    private String url;


    HttpFileHandle(String url) {
        this.url = url;
    }


    protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        if (!request.getDecoderResult().isSuccess()) {
            sendError(ctx, HttpResponseStatus.BAD_REQUEST);
            return;
        }
        if (request.getMethod() != HttpMethod.GET) {
            sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
            return;
        }

        final String requestUri = request.getUri();
        final String absolutePath = sanitizeUri(requestUri);

        if (absolutePath == null) {
            sendError(ctx, FORBIDDEN);
            return;
        }
        File file = new File(absolutePath);

        if (file.isHidden() || !file.exists()) {
            sendError(ctx, HttpResponseStatus.NOT_FOUND);
            return;
        }

        if (file.isDirectory()) {
            if (requestUri.endsWith("/")) {
                sendHtmlList(ctx, file);
            }
            else {
                sendRedirect(ctx, requestUri + '/');
            }
            return;
        }

        if (!file.isFile()) {
            sendError(ctx, FORBIDDEN);
            return;
        }

        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
        long length = randomAccessFile.length();
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK);
        HttpHeaders.setContentLength(response, length);

        MimetypesFileTypeMap typeMap = new MimetypesFileTypeMap();
        response.headers().set(HttpHeaders.Names.CONTENT_TYPE, typeMap.getContentType(file.getPath()));

        if (HttpHeaders.isKeepAlive(request)) {
            response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        }

        // 此处为临时替代代码

        FileInputStream is = new FileInputStream(absolutePath);
        // 设定读取的字节数
        int n = (int)file.length();
        byte buffer[] = new byte[n];
        // 读取输入流
        while ((is.read(buffer, 0, n) != -1) && (n > 0)) {
            System.out.print(new String(buffer));
        }
        System.out.println();
        // 关闭输入流
        is.close();

        ctx.write(response);
        response.content().writeBytes(buffer);
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);

        // 下述代码目前有些问题 后续需要研究ChunkedFile使用方式!!! 2016/7/14 Add by tantexixan
//        ChannelFuture future =
//                ctx.write(new ChunkedFile(randomAccessFile, 0, fileSize, 8192), ctx.newProgressivePromise());
//        future.addListener(new ChannelProgressiveFutureListener() {
//            public void operationComplete(ChannelProgressiveFuture channelProgressiveFuture)
//                    throws Exception {
//                System.out.println("Transfer complete.");
//
//            }
//
//
//            public void operationProgressed(ChannelProgressiveFuture channelProgressiveFuture, long progress,
//                    long total) throws Exception {
//                if (total < 0) {
//                    System.err.println("Transfer progress: " + progress);
//                }
//                else {
//                    System.err.println("Transfer progress: " + progress + "/" + total);
//                }
//            }
//
//        });
//        ChannelFuture lastfuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
//        if (!HttpHeaders.isKeepAlive(request)) {
//            lastfuture.addListener(ChannelFutureListener.CLOSE);
//        }

    }

    private static final Pattern ALLOWED_FILE_NAME_PATTERN = Pattern.compile("[A-Za-z0-9][-_A-Za-z0-9\\.]*");


    private static void sendHtmlList(ChannelHandlerContext ctx, File dir) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK);
        response.headers().set(CONTENT_TYPE, "text/html;charset=UTF-8");
        StringBuilder htmlBuf = new StringBuilder();
        String path = dir.getPath();
        htmlBuf.append("<!DOCTYPE html>\r\n");
        htmlBuf.append("<html><head><title>");
        htmlBuf.append(path);
        htmlBuf.append("目录：");
        htmlBuf.append("</title></head><body>\r\n");
        htmlBuf.append(path).append(" 目录： ");
        htmlBuf.append("</h3>\r\n");
        htmlBuf.append("<ul>");
        htmlBuf.append("<li>链接：<a href=\"../\">..</a></li>\r\n");

        for (File f : dir.listFiles()) {
            if (f.isHidden() || !f.canRead()) {
                continue;
            }
            String name = f.getName();
            if (!ALLOWED_FILE_NAME_PATTERN.matcher(name).matches()) {
                continue;
            }
            htmlBuf.append("<li>链接：<a href=\"");
            htmlBuf.append(name);
            htmlBuf.append("\">");
            htmlBuf.append(name);
            htmlBuf.append("</a></li>\r\n");
        }
        htmlBuf.append("</ul></body></html>\r\n");
        ByteBuf byteBuf = Unpooled.copiedBuffer(htmlBuf, CharsetUtil.UTF_8);
        response.content().writeBytes(byteBuf);
        byteBuf.release();
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }


    private static void sendRedirect(ChannelHandlerContext ctx, String newUri) {
        FullHttpResponse response =
                new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND);
        response.headers().set(LOCATION, newUri);
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }


    private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
        String msg = "Failure: " + status.toString() + "\r\n";
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
            Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));
        response.headers().set(CONTENT_TYPE, "text/plain;charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private static final Pattern INSECURE_URI = Pattern.compile(".*[<>&\"].*");


    private String sanitizeUri(String uri) {
        try {
            uri = URLDecoder.decode(uri, "UTF-8");
        }
        catch (Exception e) {
            try {
                uri = URLDecoder.decode(uri, "ISO-8859-1");
            }
            catch (Exception e2) {
                throw new Error();
            }
        }

        if (!uri.startsWith(url)) {
            return null;
        }

        if (!uri.startsWith("/")) {
            return null;
        }

        uri = uri.replace('/', File.separatorChar);

        if (uri.contains('.' + File.separator) || uri.startsWith(".") || uri.endsWith(".")
                || INSECURE_URI.matcher(uri).matches()) {
            return null;
        }
        return System.getProperty("user.dir") + uri;
    }


    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        if (ctx.channel().isActive()) {
            sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
